#!/bin/bash -e

# This script is indented to run the undertaker on a whole linux
# tree. It will determine which files to be processed and how many
# threads can be started according to the count of processors your
# machine has. It assumes, that you have run undertaker-kconfigdump
# before, in order to create the models.
#

while getopts :t:m:a:c OPT; do
    case $OPT in
        m)
            MODELS="$OPTARG"
            ;;
        a)
            DEFAULT_ARCH="$OPTARG"
            ;;
        t)
            PROCESSORS="$OPTARG"
            ;;
        c)
            COVERAGE=t
            ;;
        *)
            echo "usage: ${0##*/} [-m DIR] [-a ARCH] [-t PROCS] [-c]"
            echo 
            echo " -m <modeldir>  Specify the directory for the models"
            echo "                 (default: models)"
            echo " -a <arch>  Default architecture to check for"
            echo "                 (default: x86)"
            echo " -t <count>   Number of analyzing processes"
            echo "                 (default: _NPROCESSORS_ONLN)"
            echo " -c  Do coverage analysis instead of dead block search"
            exit 2
    esac
done
shift $(( OPTIND - 1 ))
OPTIND=1

MODELS=${MODELS:-models}
DEFAULT_ARCH=${DEFAULT_ARCH:-x86}
PROCESSORS=${PROCESSORS:-$(getconf _NPROCESSORS_ONLN)}

if [ ! -f arch/x86/Kconfig ]; then
    echo "Not run in an linux tree. Please run inside an linux tree without arguments"
    exit 1
else
    echo "Running on Linux Version $(git describe || echo '(no git)')"
fi

if ! which  undertaker2 > /dev/null; then
    echo "No undertaker binary found."
    exit 1
fi

if ! ls "$MODELS"/*.model >/dev/null 2>&1; then
    echo "No models found, please call undertaker-kconfigdump"
    exit
fi

find . -name "*.[hcS]" | shuf > undertaker-worklist
#find . -name '*dead' -exec rm -f {} +


if [ -n "$COVERAGE" ]; then
    echo "Running coverage analysis"
    time undertaker2 -c -t "$PROCESSORS" -b undertaker-worklist \
        -m "$MODELS" 2>/dev/null | \
  	    grep -v '^I:' |	grep -v '^Ignoring' | grep './' > coverage.txt

    echo "TOP 50 variable files (format: #possible solutions, filename)"
    awk '/^S: / {print $2}' < coverage.txt | \
	    awk -F, '{ printf "%s %s\n", $3, $1 }' | \
	    sort -n -r | \
	    head -n 50 | tee coverage.stats
else 
    echo "Analyzing $(wc -l < undertaker-worklist) files with $PROCESSORS threads."
    time undertaker2 -t "$PROCESSORS" -b undertaker-worklist -m "$MODELS" 
    printf "\n\nFound %s global defects\n" "$(find . -name '*dead.M'| grep globally | wc -l)"
fi
